package jp.sinya.register.service;

import jp.sinya.register.bean.User;
import jp.sinya.register.dao.DaoFactory;
import jp.sinya.register.dao.UserDao2;
import jp.sinya.register.exception.UserException;

public class UserService {

    //在没使用数据库之前的保存方式： 使用的是xml文件通过io流读写的方式保存。
    //private UserDao userDao = new UserDao();
    private UserDao2 userDao = DaoFactory.getUserDao();

    public void register(User user) throws UserException {
        User queryUser = userDao.findUserByName(user.getUsername());
        if (queryUser != null) {
            throw new UserException("用户名:" + user.getUsername() + "已经被注册");
        }
        userDao.addUser(user);
    }

    public User login(User user) throws UserException {
        if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            throw new UserException("用户名为空");
        }
        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            throw new UserException("登陆密码为空");
        }
        User queryUser = userDao.findUserByName(user.getUsername());
        if (queryUser == null) {
            throw new UserException("该用户不存在");
        }
        if (!user.getPassword().equals(queryUser.getPassword())) {
            throw new UserException("密码错误");
        }

        return queryUser;
    }


}
